﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.ComponentModel;
using System.Reflection;

public static class Common 
{
    public static T AddCompontentIfNoExist<T>(this GameObject go) where T : UnityEngine.Component
    {
        if (go.GetComponent<T>() == null)
            go.AddComponent<T>();
        return go.GetComponent<T>();
    }

    public static int GetFontLen(Font font,int fontsize, string str)
    {
        if (string.IsNullOrEmpty(str))
            return 0;
        int len = 0;
        font = Font.CreateDynamicFontFromOSFont("Arial", fontsize);
        font.RequestCharactersInTexture(str);
        for (int i = 0; i < str.Length; i++)
        {
            CharacterInfo ch;
            font.GetCharacterInfo(str[i], out ch);
            len += ch.advance;
        }
        return len;
    }

    public static void Resize(this RectTransform trans, float x = 0, float y = 0)
    {
        if (x == 0)
            x = trans.sizeDelta.x;
        if (y == 0)
            y = trans.sizeDelta.y;
        trans.sizeDelta = new Vector2(x, y);
    }

    public static T GetNearestCompontentInParent<T>(this GameObject go) where T : UnityEngine.Component
    {
        if (go.GetComponent<T>() == null)
            return go.GetComponentInParent<T>();
        T[] ss = go.GetComponentsInParent<T>();
        if (ss.Length >= 2)
            return ss[1];
        return null;
    }

    /// <summary>
    /// 获取枚举类子项描述信息
    /// </summary>
    /// <param name="enumSubitem">枚举类子项</param>        
    public static string GetEnumDescription(Enum enumSubitem)
    {
        string strValue = enumSubitem.ToString();
        FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue);
        System.Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (objs == null || objs.Length == 0)
        {
            return strValue;
        }
        else
        {
            DescriptionAttribute da = (DescriptionAttribute)objs[0];
            return da.Description;
        }
    }
}
